import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Textarea } from '../ui/textarea';
import { Label } from '../ui/label';
import { Input } from '../ui/input';
import { 
  Calendar, 
  Clock, 
  CheckCircle, 
  XCircle, 
  AlertCircle,
  FileText,
  Plus,
  Download
} from 'lucide-react';

interface AttendanceRecord {
  id: string;
  courseName: string;
  date: string;
  time: string;
  status: 'present' | 'absent' | 'late' | 'leave';
  teacher: string;
  location: string;
  note?: string;
}

interface LeaveRequest {
  id: string;
  type: string;
  startDate: string;
  endDate: string;
  reason: string;
  status: 'pending' | 'approved' | 'rejected';
  submitDate: string;
  approver?: string;
  note?: string;
}

export function AttendanceRecord() {
  const [selectedSemester, setSelectedSemester] = useState('2024-1');
  const [selectedStatus, setSelectedStatus] = useState('all');
  const [showLeaveForm, setShowLeaveForm] = useState(false);

  const attendanceRecords: AttendanceRecord[] = [
    {
      id: '1',
      courseName: '高等数学A',
      date: '2024-03-15',
      time: '08:00-09:40',
      status: 'present',
      teacher: '陈教授',
      location: '教学楼A-101'
    },
    {
      id: '2',
      courseName: '计算机程序设计',
      date: '2024-03-14',
      time: '10:00-11:40',
      status: 'late',
      teacher: '张老师',
      location: '实验楼B-201',
      note: '迟到5分钟'
    },
    {
      id: '3',
      courseName: '大学英语',
      date: '2024-03-13',
      time: '14:00-15:40',
      status: 'leave',
      teacher: '李老师',
      location: '语音教室C-301',
      note: '病假'
    },
    {
      id: '4',
      courseName: '线性代数',
      date: '2024-03-12',
      time: '10:00-11:40',
      status: 'absent',
      teacher: '王教授',
      location: '教学楼A-203',
      note: '旷课'
    }
  ];

  const leaveRequests: LeaveRequest[] = [
    {
      id: '1',
      type: '病假',
      startDate: '2024-03-13',
      endDate: '2024-03-13',
      reason: '感冒发烧，需要休息治疗',
      status: 'approved',
      submitDate: '2024-03-12',
      approver: '李老师',
      note: '已提供医院证明'
    },
    {
      id: '2',
      type: '事假',
      startDate: '2024-03-20',
      endDate: '2024-03-21',
      reason: '家中有事需要回家处理',
      status: 'pending',
      submitDate: '2024-03-18'
    }
  ];

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'present':
        return <Badge className="bg-green-100 text-green-800"><CheckCircle className="w-3 h-3 mr-1" />出勤</Badge>;
      case 'absent':
        return <Badge variant="destructive"><XCircle className="w-3 h-3 mr-1" />旷课</Badge>;
      case 'late':
        return <Badge variant="outline"><Clock className="w-3 h-3 mr-1" />迟到</Badge>;
      case 'leave':
        return <Badge variant="secondary"><FileText className="w-3 h-3 mr-1" />请假</Badge>;
      default:
        return <Badge variant="outline">未知</Badge>;
    }
  };

  const getLeaveStatusBadge = (status: string) => {
    switch (status) {
      case 'approved':
        return <Badge className="bg-green-100 text-green-800">已批准</Badge>;
      case 'rejected':
        return <Badge variant="destructive">已驳回</Badge>;
      case 'pending':
        return <Badge variant="outline">待审批</Badge>;
      default:
        return <Badge variant="outline">未知</Badge>;
    }
  };

  const filteredRecords = attendanceRecords.filter(record => {
    const matchesStatus = selectedStatus === 'all' || record.status === selectedStatus;
    return matchesStatus;
  });

  const getAttendanceStats = () => {
    const total = attendanceRecords.length;
    const present = attendanceRecords.filter(r => r.status === 'present').length;
    const rate = total > 0 ? ((present / total) * 100).toFixed(1) : '0.0';
    return { total, present, rate };
  };

  const stats = getAttendanceStats();

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-medium">考勤与请假</h1>
        <div className="flex gap-2">
          <Button variant="outline">
            <Download className="mr-2 h-4 w-4" />
            导出考勤记录
          </Button>
          <Button onClick={() => setShowLeaveForm(true)}>
            <Plus className="mr-2 h-4 w-4" />
            申请请假
          </Button>
        </div>
      </div>

      {/* Statistics Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">出勤率</p>
                <p className="text-2xl font-medium">{stats.rate}%</p>
              </div>
              <CheckCircle className="h-8 w-8 text-green-500" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">总课时</p>
                <p className="text-2xl font-medium">{stats.total}</p>
              </div>
              <Calendar className="h-8 w-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">正常出勤</p>
                <p className="text-2xl font-medium">{stats.present}</p>
              </div>
              <Clock className="h-8 w-8 text-orange-500" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">请假次数</p>
                <p className="text-2xl font-medium">{attendanceRecords.filter(r => r.status === 'leave').length}</p>
              </div>
              <FileText className="h-8 w-8 text-purple-500" />
            </div>
          </CardContent>
        </Card>
      </div>

      <Tabs defaultValue="records" className="space-y-4">
        <TabsList>
          <TabsTrigger value="records">考勤记录</TabsTrigger>
          <TabsTrigger value="leave">请假管理</TabsTrigger>
        </TabsList>

        <TabsContent value="records" className="space-y-4">
          {/* Filter */}
          <Card>
            <CardContent className="p-4">
              <div className="flex gap-4 items-center">
                <div className="flex gap-2 items-center">
                  <label className="text-sm font-medium">学期:</label>
                  <Select value={selectedSemester} onValueChange={setSelectedSemester}>
                    <SelectTrigger className="w-40">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="2024-1">2024年第一学期</SelectItem>
                      <SelectItem value="2023-2">2023年第二学期</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                
                <div className="flex gap-2 items-center">
                  <label className="text-sm font-medium">状态:</label>
                  <Select value={selectedStatus} onValueChange={setSelectedStatus}>
                    <SelectTrigger className="w-32">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">全部</SelectItem>
                      <SelectItem value="present">出勤</SelectItem>
                      <SelectItem value="absent">旷课</SelectItem>
                      <SelectItem value="late">迟到</SelectItem>
                      <SelectItem value="leave">请假</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Attendance Table */}
          <Card>
            <CardHeader>
              <CardTitle>考勤记录</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>课程名称</TableHead>
                    <TableHead>日期</TableHead>
                    <TableHead>时间</TableHead>
                    <TableHead>教师</TableHead>
                    <TableHead>地点</TableHead>
                    <TableHead>考勤状态</TableHead>
                    <TableHead>备注</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredRecords.map((record) => (
                    <TableRow key={record.id}>
                      <TableCell className="font-medium">{record.courseName}</TableCell>
                      <TableCell>{record.date}</TableCell>
                      <TableCell>{record.time}</TableCell>
                      <TableCell>{record.teacher}</TableCell>
                      <TableCell>{record.location}</TableCell>
                      <TableCell>{getStatusBadge(record.status)}</TableCell>
                      <TableCell className="text-sm text-muted-foreground">{record.note || '-'}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="leave" className="space-y-4">
          {/* Leave Requests */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                请假申请记录
                <Button size="sm" onClick={() => setShowLeaveForm(true)}>
                  <Plus className="mr-2 h-4 w-4" />
                  新建申请
                </Button>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {leaveRequests.map((request) => (
                  <div key={request.id} className="p-4 border rounded-lg">
                    <div className="flex justify-between items-start mb-2">
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <Badge variant="outline">{request.type}</Badge>
                          {getLeaveStatusBadge(request.status)}
                        </div>
                        <p className="text-sm text-muted-foreground">
                          {request.startDate} {request.startDate !== request.endDate && `至 ${request.endDate}`}
                        </p>
                      </div>
                      <p className="text-sm text-muted-foreground">申请时间: {request.submitDate}</p>
                    </div>
                    
                    <p className="text-sm mb-2">{request.reason}</p>
                    
                    {request.status === 'approved' && request.approver && (
                      <p className="text-sm text-green-600">审批人: {request.approver}</p>
                    )}
                    
                    {request.note && (
                      <p className="text-sm text-muted-foreground">备注: {request.note}</p>
                    )}
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Leave Request Form Modal */}
      {showLeaveForm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
          <Card className="w-full max-w-md">
            <CardHeader>
              <CardTitle>请假申请</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label htmlFor="leave-type">请假类型</Label>
                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="选择请假类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="sick">病假</SelectItem>
                    <SelectItem value="personal">事假</SelectItem>
                    <SelectItem value="other">其他</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="start-date">开始日期</Label>
                  <Input type="date" id="start-date" />
                </div>
                <div>
                  <Label htmlFor="end-date">结束日期</Label>
                  <Input type="date" id="end-date" />
                </div>
              </div>
              
              <div>
                <Label htmlFor="reason">请假原因</Label>
                <Textarea 
                  id="reason"
                  placeholder="请详细说明请假原因..."
                  rows={3}
                />
              </div>
              
              <div className="flex gap-2 pt-4">
                <Button className="flex-1">提交申请</Button>
                <Button variant="outline" onClick={() => setShowLeaveForm(false)}>取消</Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  );
}